<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    :title="title"
    width="600"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-align="right"
      label-width="120"
      label-position="left"
    >
      <el-form-item label="海关商品码" prop="customs_goods_code">
        <el-input
          v-model="form.customs_goods_code"
          placeholder="请输入"
          clearable
          oninput="value=value.replace(/[^0-9]/g,'')"
        />
      </el-form-item>

      <el-form-item label="标准商品全名">
        <el-input v-model="form.goods_name" placeholder="请输入" clearable />
      </el-form-item>

      <el-form-item label="商品码单位">
        <el-input v-model="form.code_unit" placeholder="请输入" clearable />
      </el-form-item>

      <el-form-item label="退税率%">
        <el-input
          v-model="form.refund_tax_rate"
          oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,2}).*/,'$1')"
          placeholder="请输入"
          clearable
        />
      </el-form-item>

      <el-form-item label="特殊商品标识">
        <el-select
          class="w-full"
          v-model="form.special_identify"
          clearable
          placeholde="请选择"
        >
          <el-option
            v-for="item in markingOptions"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="备注">
        <el-input
          v-model="form.remark"
          placeholder="请输入"
          type="textarea"
          clearable
          :autosize="{ minRows: 4, maxRows: 6 }"
        />
      </el-form-item>

      <el-form-item label="申报要素维护项" required>
        <div
          class="flex"
          v-for="(item, index) in form.declare_elements_list"
          :key="index"
        >
          <div
            class="w-[60px] h-[34px] border border-[var(--base-border-color)] text-center"
          >
            {{ index }}
          </div>
          <div>
            <el-input
              class="w-[300px]"
              placeholder="请输入"
              v-model="item.text"
            ></el-input>
          </div>
          <div class="w-20 flex ml-2">
            <svg-icon
              class="w-4 mt-2 icon icon-color"
              @click="handleCreate()"
              icon-class="add03"
            />
            <svg-icon
              class="w-4 mt-2 icon mr-3 ml-3"
              @click="handleDelete(index)"
              icon-class="jian"
            />
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save(formRef)"
        >保 存</el-button
      >
    </template>
  </el-dialog>
</template>
<script setup name="ComModal" lang="jsx">
import { reactive, toRefs } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { filterDeleteFlag } from "@/utils/index.js";
import { getCustomsDetail, createCustoms, updateCustoms } from "../api.js";
import { markingOptions } from "../data.js";
const emits = defineEmits(["query"]);
const data = reactive({
  form: {},
  visible: false,
  loading: false,
  formRef: null,
  rules: {
    customs_goods_code: [{ required: true, message: "请输入海关编码" }],
  },
  handleType: "",
  title: "",
  load: false,
});
const { rules, form, visible, loading, formRef, handleType, title, load } = toRefs(data);

const statusMap = new Map([
  ["add", "新增"],
  ["edit", "编辑"],
  ["view", "查看"],
]);

const open = async (type, id) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  title.value = statusMap.get(type);
  handleType.value = type;
  visible.value = true;
  initForm();
  if (id) getDetail(id);
};

const getDetail = async (id) => {
  try {
    const res = await getCustomsDetail({
      id,
    });
    form.value = res.data;
    if (form.value.declare_elements_list.length == 0) {
      form.value.declare_elements_list.push({
        text: "",
      });
    }
  } catch (e) {
    throw Error(e);
  }
};

const save = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      const formData = Object.assign({}, form.value);
      const messageArray = [];
      formData.declare_elements_list.forEach((item, index) => {
        if (!item.text) {
          messageArray.push(`申报要素: 第${index}项，内容不能为空`);
        }
      });

      if (messageArray && messageArray.length) {
        ElMessageBox({
          title: "提示",
          message: () => <div>{messageArray.map((d) => h("p", null, d))}</div>,
        });
        return;
      }
      formData.declare_elements_list = formData.declare_elements_list.map(
        (item, index) => {
          item.sort = index;
          return item;
        }
      );

      if (formData.id) {
        updateCustoms(formData)
          .then((res) => {
            ElMessage.success(res.message);
            emits("query");
            close();
          })
          .finally(() => {
            loading.value = false;
          });
      } else {
        createCustoms(formData)
          .then((res) => {
            ElMessage.success(res.message);
            emits("query");
            close();
          })
          .finally(() => {
            loading.value = false;
          });
      }
    }
  });
};

const initForm = () => {
  form.value = getForm();
};
// 初始化
const getForm = () => {
  return {
    name: "",
    currency: "",
    exchange_type: "",
    exchange_rate: "",
    declare_elements_list: [
      {
        text: "",
      },
    ],
  };
};

onMounted(() => {
  initForm();
});

const close = () => {
  initForm();
  visible.value = false;
};
defineExpose({ open });

// 新增
const handleCreate = () => {
  if (form.value.declare_elements_list.length == 20) {
    return ElMessage.warning("最多只能添加20条数据");
  }
  form.value.declare_elements_list.push({
    text: "",
  });
};

// 删除
const handleDelete = (index) => {
  if (filterDeleteFlag(form.value.declare_elements_list)) {
    ElMessage.error("至少保留一条");
    return;
  }
  form.value.declare_elements_list.splice(index, 1);
};
</script>
<style></style>
